import React from "react";
import { messages } from "share/common";
import { Col, Row, Select } from "antd";
import MultiSelector from "components/multi-selector";

const Option = Select.Option;
const { Component, PropTypes } = React;

export const labelsSelectorHasValue = value => value && value.contains !== undefined && value.selectedLabels && value.selectedLabels.length;
export const labelsSelectorTagParser = (value) => {
  value = value || {};
  const { contains, selectedLabels = [] } = value;
  if (contains === '1001') {
    return messages('finance-7.key294',{arg1: selectedLabels.length})/*包含{arg1}条*/
  } else {
    return messages('finance-7.key295',{arg1: selectedLabels.length})/*不包含{arg1}条*/
  }
};

export const labelsSelectorTransfer = ({ value }) => {
  value = value || {};
  const { contains, selectedLabels = [] } = value;
  if (contains === undefined) return undefined;
  return JSON.stringify({
    contains: contains === '1001',
    labelCode: selectedLabels.map(item => item.value)
  });
};

class LabelsSelector extends Component {

  constructor(props) {
    super(props);
    this.state = {
      contains: (props.value || {}).contains,
      selectedLabels: []
    };
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.value) {
      this.setState({
        contains: undefined,
        selectedLabels: []
      })
    }
  }

  onContainsChange = (contains) => {
    let {selectedLabels} = this.state;
    if (!contains) {
      selectedLabels = [];
    }
    this.setState({
      contains,
      selectedLabels
    }, this.onChange)
  };

  onLabelsChange = (selectedLabels) => {
    this.setState({
      selectedLabels
    }, this.onChange)
  };

  onChange = () => {
    const { contains, selectedLabels } = this.state;
    let result = {
      contains,
      selectedLabels
    };
    this.props.onChange(result);
  };

  render() {
    const { selectorItem } = this.props;
    const { contains, selectedLabels } = this.state;
    return (
      <Row gutter={10}>
        <Col span={10}>
          <Select
            allowClear
            style={{ width: '100%' }}
            onChange={this.onContainsChange}
            value={contains}
            placeholder={messages('common.select')/*请选择*/}
            getPopupContainer={triggerNode => triggerNode.parentNode}
          >
            <Option key="1001">{messages('finance-7.key296')/*包含*/}</Option>
            <Option key="1002">{messages('finance-7.key297')/*不包含*/}</Option>
          </Select>
        </Col>
        <Col span={14} style={{ height: 32 }}>
          <MultiSelector
            allowClear
            disabled={!contains}
            selectorItem={selectorItem}
            onChange={this.onLabelsChange}
            value={selectedLabels}
          />
        </Col>
      </Row>
    )
  }

  static propsType = {
    selectorItem: PropTypes.object,
  };

  static defaultProps = {};
}

export default LabelsSelector;
